const app = getApp()
import {
  BASE_API
} from "../../../utils/config";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    BASE_IMAGE_API: app.globalData.BASE_IMAGE_API,
    userInfo: wx.getStorageSync('userInfo'), //个人信息
    localUserInfo: {
      headImgUrl: '',
      nickname: '',
    },
    exclusivelist: [],

    showCustomerServicePopUp: false, //敬请期待
    showaAtionSheet: false, //弹出登录提示
    applyForInformation: false, //获取用户信息
  },
  onLoad() {
    let self = this;
    if (!app.globalData.plumSession) {
      //未检测到  self.globalData.plumSession
      //创建 app.plumSessionCallback 的回调函数，将plumSession作为函数参数，app.js中检测到函数被创建，
      app.plumSessionCallback = plumSession => {
        if (plumSession != '') {
          console.log("self.getIndexImgList()")
        } else {
          app.wechatSq(self);
        }
      }
    } else {
      console.log("self.getIndexImgList()")
    }
  },
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3,
        show: true,
      })
    }
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
    let {
      userInfo
    } = this.data
    if (!userInfo.authorizedPrivacy) {
      this.setData({
        showaAtionSheet: true,
        applyForInformation: false,
      })
    } else {
      this.setData({
        showaAtionSheet: false
      })
    }

  },
  
  /**
   * 小程序用户信息接口
   */
  async getUser() {
    let resolve = await getUser("GET")
    wx.setStorageSync('userInfo', resolve)
    this.setData({
      userInfo: resolve
    })
  },
  /**
   * 添加用户信息
   */
  async updateById(userInfo) {
    let resolve = await updateById("POST", {
      nickname: userInfo.nickName,
      sex: userInfo.gender == 1 ? 'M' : userInfo.gender == 2 ? 'F' : '',
      headImgUrl: userInfo.avatarUrl,
      id: this.data.userInfo.id
    })
    this.getUser()
  },
  contactCustomerService(e) {
    this.setData({
      showCustomerServicePopUp: true,
    })
  },
  stop() {
    console.log('stop');
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    this.setData({
      ['localUserInfo.headImgUrl']: avatarUrl
    })
  },
  inpName(e) {
    const {
      value
    } = e.detail
    this.setData({
      ['localUserInfo.nickname']: value
    })
  },
  blurName(e) {
    const {
      value
    } = e.detail
    this.setData({
      ['localUserInfo.nickname']: value
    })
  },
  /**
   * 获取用户信息接口
   */
  infoSave() {
    let self = this
    let {
      localUserInfo
    } = self.data
    wx.uploadFile({
      //请求后台的路径
      url: `${BASE_API}/wx/user/${AppID}/infoSave`,
      header: {
        'content-type': "multipart/form-data",
        "X-Requested-With": "XMLHttpRequest",
        "gs_shop_mini_user_token": wx.getStorageSync('gs_shop_mini_user_token'),
      },
      filePath: localUserInfo.headImgUrl,
      //后台获取我们图片的key
      name: 'headImgUrl',
      formData: {
        nickname: localUserInfo.nickname
      },
      success: function (res) {
        console.log(res);
        if (res.statusCode == 200) {
          self.authorizedPrivacy()
        }
      },
      fail: function (res) {
        console.log(res);
      },
    })
    // let resolve = await infoSave("GET",localUserInfo)
    // this.authorizedPrivacy()
  },
  async uploadInfoSave() {
    let self = this
    let {
      localUserInfo
    } = self.data
    let resolve = await uploadInfoSave(`/wx/user/${AppID}/infoSave`, localUserInfo.headImgUrl, 'headImgUrl', localUserInfo)
    console.log(resolve);
    if (resolve.statusCode == 200) {
      self.authorizedPrivacy()
    }
  },
  /**
   * 授权
   */
  async authorizedPrivacy() {
    let resolve = await authorizedPrivacy("GET")
    this.closeActionSheet()
    if (resolve.success) {
      wx.showToast({
        title: '授权成功',
        icon: 'none',
        duration: 2000,
        mask: true
      })
    }
    this.getUser()
  },
  applyForInformation() {
    this.setData({
      applyForInformation: true,
      showaAtionSheet: false,
    })
  },
  saveUserInfo() {
    let {
      localUserInfo
    } = this.data
    if (!localUserInfo.headImgUrl) {
      wx.showToast({
        title: '请选择用户头像',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    if (!localUserInfo.nickname) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    // this.infoSave()
    this.uploadInfoSave()
  },
  closeActionSheet() {
    this.setData({
      showaAtionSheet: false,
      applyForInformation: false,
    })
  },
  openLoginTip() {
    this.setData({
      showaAtionSheet: true,
    })
  },
  goGoodsDetails(e) {
    let {
      url,
      id,
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `${url}?id=${id}`,
    })
  },
  goPath(e) {
    let {
      url,
      index,
    } = e.currentTarget.dataset
    if (!url) {
      this.setData({
        showCustomerServicePopUp: true,
      })
      return
    }
    wx.navigateTo({
      url: `${url}`,
    })
  },
  openFile(e) {
    let {
      name,
      title
    } = e.currentTarget.dataset
    // 加载状态
    wx.showLoading({
      title: '文件打开中',
      mask: true
    });
    wx.downloadFile({
      // 示例 url，并非真实存在
      url: `${BASE_API}/pdf/${name}`,
      filePath: `${wx.env.USER_DATA_PATH}/${title}`,
      success: function (res) {
        const filePath = res.filePath
        wx.openDocument({
          filePath: filePath,
          showMenu: true,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function () {
            console.log('打开文件失败，请稍后重试')
          }
        })
        wx.hideLoading();
      },
      fail: function () {
        wx.hideLoading();
        wx.showToast({
          title: '打开文件失败，请稍后重试',
          icon: 'none'
        })
      }
    })
  }
})